package com.ktjy.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    static SqlSessionFactory sesessionFactory=null;

    static {
        //1.创建一个sesssionFactoryBuilder对象
        //SqlSessionFactoryBuilder只要用一次就好（用完就销毁）
        SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
        //2.读取mybaits的核心配置文件
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //3.创建SqlSessionFactory对象
        //SqlSessionFactory只要创建一次，但是反复使用（定义为全局变量，但是赋值支只赋一次）
        sesessionFactory= builder.build(resourceAsStream);
    }

    public static SqlSession createSqlSession(){
        return sesessionFactory.openSession(false);
    }

    public static void closeSqlSession(SqlSession session){
        if(session!=null){
            session.close();
        }
    }
}
